package cn.jc.myfile.common.validation;

import org.springframework.stereotype.Component;

import javax.validation.constraints.Size;
import java.lang.reflect.Field;

@Component
public class SizeValidator implements cn.jc.myfile.common.validation.Validator<Size> {

    @Override
    public Class<Size> supportAnnotation() {
        return Size.class;
    }

    @Override
    public void validate(Object target, Field field, Size annotation) {
        try{
            field.setAccessible(true);
            String fieldName = field.getName();
            Object o = field.get(target);
            if(o !=null){
                if(!(o instanceof CharSequence)){
                    throw new RuntimeException("Size注解字段类型不正确！");
                }
                Integer min = annotation.min();
                Integer max = annotation.max();
                int size=((CharSequence) o).length();
                if(size < min){
                    throw new RuntimeException(fieldName+":不能小于"+min+"字符！");
                }
                if(size > max){
                    throw new RuntimeException(fieldName+":不能超过"+max+"字符！");
                }
            }
        }catch(Exception ex) {
            if(ex instanceof RuntimeException){
                throw new RuntimeException(ex.getMessage());
            }else{
                throw new RuntimeException("校验异常！");
            }
        }finally {
            field.setAccessible(false);
        }
    }
}
